import chalk from 'chalk'
import path from 'path'
import fs from 'fs'
import shell from 'shelljs'
import inquirer from 'inquirer'

const resolve = (__dirname, ...file) => path.resolve(__dirname, ...file)
const log = (message) => console.log(chalk.green(`${message}`))
const successLog = (message) => console.log(chalk.blue(`${message}`))
const errorLog = (error) => console.log(chalk.red(`${error}`))

const pagePath = 'page'

log('请输入要生成的"模块名称"、会生成在 /page 目录下')
const questions = [
  {
    type: 'input',
    name: 'name',
    message: '请输入要生成的模块名称:',
    validate: function (input) {
      const isValidFileName = /^[a-zA-Z][a-zA-Z0-9_\-]*$/.test(input)
      if (!isValidFileName) {
        return '文件名不合法，请重新输入。'
      }
      const pages = fs.readdirSync(path.resolve('./page'))
      if (pages.includes(input)) {
        return '项目已存在，请修改输入名称。'
      }
      return true
    }
  },
  {
    type: 'list',
    name: 'template',
    message: '请选择你想创建的模板:',
    choices: [
      { name: '普通模板', value: 'master' },
      { name: '后台管理模板', value: 'admin' },
      { name: '两者都要', value: 'common' }
    ],
    default: 'admin'
  }
]

inquirer.prompt(questions).then(async (answers) => {
  console.log(answers)
  const pages = fs.readdirSync(path.resolve('./page'))
  const projectName = answers.name
  if (!projectName || pages.includes(projectName)) {
    errorLog('模块已经存在')
    return
  }

  const targetPath = resolve('./page', projectName)
  fs.mkdirSync(targetPath)
  successLog(`已在 /page 目录下创建 ${projectName} 文件夹。`)
  copyFile(`config/scripts/template/${answers.template}`, targetPath)
  successLog(`模板导入成功。`)
  setFile()
  async function setFile() {
    // 修改项目中/router/inbex.ts的文件内容
    try {
      const routerPath = resolve(targetPath, './router/index.ts')
      const data = await fs.promises.readFile(routerPath, 'utf8')
      const modifiedData = data.replace(/\{{pagePath}}/, `/${projectName}`)
      await fs.promises.writeFile(routerPath, modifiedData, 'utf8')
      successLog(`路由basePath配置成功。`)
    } catch (err) {
      errorLog(`路由basePath修改失败。请自行检查修改。`)
    }

    try {
      const _path = resolve('./', 'tsconfig.json')
      const json = await fs.promises.readFile(_path, 'utf8')
      let modifiedJson = JSON.parse(json.replace(/'/g, '"'))
      modifiedJson.compilerOptions.paths[`@${projectName}/*`] = [`./page/${projectName}/*`]
      modifiedJson = JSON.stringify(modifiedJson, null, 2)
      await fs.promises.writeFile(_path, modifiedJson, 'utf8')
      const prettierCommand = `npx prettier --write tsconfig.json`
      shell.exec(prettierCommand)
      successLog(`tsconfig.json配置成功。`)
    } catch (err) {
      errorLog(`tsconfig.json文件paths添加失败, 请自行检查添加。`)
    }

    log(`${projectName}模块创建完毕。`)
  }
})

// process.stdin.on('data', async (chunk) => {
//   const pagePath = 'page'
//   const pages = fs.readdirSync(path.resolve('./page'))
//   // 获取输入的信息
//   const projectName = String(chunk).trim().toString()

//   if (!projectName || pages.includes(projectName)) {
//     errorLog('模块已经存在，请重新输入')
//     return
//   }
//   successLog(`将在 /page 目录下创建 ${projectName} 文件夹`)
//   const targetPath = resolve('./page', projectName)
//   fs.mkdirSync(targetPath)
//   copyFile('config/scripts/template/admin', targetPath)
//   setFile()
//   async function setFile() {
//     // 修改项目中/router/inbex.ts的文件内容
//     try {
//       const routerPath = resolve(targetPath, './router/index.ts')
//       const data = await fs.promises.readFile(routerPath, 'utf8')
//       const modifiedData = data.replace(/\{{pagePath}}/, `/${projectName}`)
//       await fs.promises.writeFile(routerPath, modifiedData, 'utf8')
//     } catch (err) {
//       errorLog(`路由basePath修改失败。请自行检查修改。`)
//     }

//     try {
//       const _path = resolve('./', 'tsconfig.json')
//       const json = await fs.promises.readFile(_path, 'utf8')
//       let modifiedJson = JSON.parse(json.replace(/'/g, '"'))
//       modifiedJson.compilerOptions.paths[`@${projectName}/*`] = [`./page/${projectName}/*`]
//       modifiedJson = JSON.stringify(modifiedJson, null, 2)
//       console.log(modifiedJson)
//       await fs.promises.writeFile(_path, modifiedJson, 'utf8')
//       const prettierCommand = `npx prettier --write tsconfig.json`
//       shell.exec(prettierCommand)
//     } catch (err) {
//       errorLog(`tsconfig.json文件paths添加失败, 请自行检查添加。`)
//     }

//     successLog(`${projectName}模块已创建`)
//     process.stdin.emit('end')
//   }
// })

// process.stdin.on('end', () => {
//   process.exit()
// })

// 判断文件夹是否存在，不存在创建一个
const isExist = (path) => {
  if (!fs.existsSync(path)) {
    fs.mkdirSync(path)
  }
}
//递归复制模版文件夹内的文件
const copyFile = (sourcePath, targetPath) => {
  const sourceFile = fs.readdirSync(sourcePath, { withFileTypes: true })

  sourceFile.forEach((file) => {
    const newSourcePath = path.resolve(sourcePath, file.name)
    const newTargetPath = path.resolve(targetPath, file.name)
    //isDirectory() 判断这个文件是否是文件夹，是就继续递归复制其内容
    if (file.isDirectory()) {
      isExist(newTargetPath)
      copyFile(newSourcePath, newTargetPath)
    } else {
      fs.copyFileSync(newSourcePath, newTargetPath)
    }
  })
}
